import 'package:flutter/material.dart';

import '../../common/api/work_order_api.dart';
import '../../common/type/data_list_container_type.dart';
import '../../common/util/common_util.dart';
import '../../page_widget/work_order_list_item.dart';
import '../../widget/search_bar.dart';
import '../../widget/data_list_container.dart';

class AssignWorkOrderPage extends StatefulWidget {
  const AssignWorkOrderPage({Key? key}) : super(key: key);

  @override
  State<AssignWorkOrderPage> createState() => AssignWorkOrderPageState();
}

class AssignWorkOrderPageState extends State<AssignWorkOrderPage> {
  GlobalKey<DataListContainerState> dataListContainerStateKey =
      GlobalKey<DataListContainerState>();

  String keyWords = '';

  List<String> idList = [];

  int pageTotal = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData(DataListContainerQueryParam param) async {
    if (null != param.currentPage && param.currentPage == 1) {
      var res = await WorkOrderApi.getWaitAssignWorkOrderNoList(
          {"keyWords": keyWords});
      if (null != res.data && res.data["isSuccess"]) {
        if (null != res.data["data"] && res.data["data"].length > 0) {
          idList = ((res.data["data"]["workOrderNos"] ?? []) as List<dynamic>)
              .cast<String>();
          pageTotal = CommonUtil.calcPageTotal(idList, param.pageSize ?? 0);
          return getDataList(param.currentPage ?? 0, param.pageSize ?? 0);
        } else {
          idList = [];
          return getDataList(0, 0);
        }
      } else {
        idList = [];
        return getDataList(0, 0);
      }
    } else {
      return getDataList(param.currentPage ?? 0, param.pageSize ?? 0);
    }
  }

  getDataList(int currentPage, int pageSize) {
    return CommonUtil.getDataList(currentPage, pageSize, pageTotal, idList,
        (list) {
      return WorkOrderApi.getWorkOrderList({
        "workOrderNos": list,
      });
    });
  }

  Widget listBodyBuilder(context, item) {
    return WorkOrderListItem(data: item, toView: (data) {
      CommonUtil.cancelFocusNodes(context);
      Navigator.of(context).pushNamed("/assignWorkOrderDetail",
          arguments: {"no": data['workOrderNo']});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("工单指派")),
      body: Column(
        children: [
          SearchBar(
              hintText: '输入发起人姓名、房间号、处理人姓名，进行搜索',
              valueChanged: (value) {
                keyWords = value;
              },
              onBtnPressed: (value) {
                dataListContainerStateKey.currentState!.refresh();
              }),
          Expanded(
              child: DataListContainer(
            key: dataListContainerStateKey,
            getData: getData,
            listBodyBuilder: listBodyBuilder,
          ))
        ],
      ),
    );
  }
}
